# -*- coding: utf-8 -*-

import mod.server.extraServerApi as serverApi

from gemstoneScripts.common.tools.weight import random_by_weight
from gemstoneScripts.config.blockList import *
from gemstoneScripts.config.itemList import *

levelId = serverApi.GetLevelId()
comp = serverApi.GetEngineCompFactory()
ServerSystem = serverApi.GetServerSystemCls()

gemstone_ore = {
    DEEPSLATE_MORGANITE_ORE: ROUGH_MORGANITE,
    DEEPSLATE_ROSE_QUARTZ_ORE: ROUGH_ROSE_QUARTZ,
    MORGANITE_ORE: ROUGH_MORGANITE,
    GEMSTONE_ROSE_QUARTZ_ORE: ROUGH_ROSE_QUARTZ,
    DEEPSLATE_SAPPHIRE_ORE: ROUGH_SAPPHIRE,
    SAPPHIRE_ORE: ROUGH_SAPPHIRE,
    DEEPSLATE_SPINEL_ORE: ROUGH_SPINEL,
    SPINEL_ORE: ROUGH_SPINEL
}

# 时运掉落随机池
FORTUNE_POOL = [1, 2, 3, 4]
# 时运掉落权重对照
FORTUNE_WEIGHT = [2, 1, 1, 1]


class Listener(ServerSystem):
    def __init__(self, namespace, system_name):
        super(ServerSystem, self).__init__(namespace, system_name)
        self.ListenEvent()
        pass

    def Destroy(self):
        self.UnListenEvent()
        pass

    def ListenEvent(self):
        self.ListenForEvent(serverApi.GetEngineNamespace(), serverApi.GetEngineSystemName(),
                            'ServerPlayerTryDestroyBlockEvent', self, self.Fortune)

    def UnListenEvent(self):
        self.UnListenForEvent(serverApi.GetEngineNamespace(), serverApi.GetEngineSystemName(),
                              'ServerPlayerTryDestroyBlockEvent', self, self.Fortune)

    def Fortune(self, args):
        block_id = args['fullName']
        # 首先判断方块是否位于时运表中，如果不位于，则直接返回
        if block_id not in gemstone_ore.keys():
            return
        player_id = args['playerId']
        comp_game = comp.CreateGame(levelId)
        # 其次判断玩家模式，如果为创造模式，直接返回
        if comp_game.GetPlayerGameType(player_id) == 1:
            return
        comp_item = comp.CreateItem(player_id)
        carried_item = comp_item.GetPlayerItem(2)
        enchants = carried_item['enchantData']
        fortune_level = 0
        # 这里获取时运等级，如果没有获取到时运附魔，则时运等级为0
        for enchant, level in enchants:
            if enchant == 18:
                fortune_level = level
                break
        # 如果时运等级为0，则直接返回
        if fortune_level == 0:
            return
        pos = (args['x'], args['y'], args['z'])
        drop_item = gemstone_ore[block_id]
        args['spawnResources'] = False
        # 根据权重随机获得物品掉落数量
        count = random_by_weight(FORTUNE_POOL, FORTUNE_WEIGHT, 0, fortune_level + 1)
        item_dict = {
            'itemName': drop_item,
            'count': count,
            'auxValue': 0
        }
        # 实体掉落
        self.CreateEngineItemEntity(item_dict, 0, pos)
        pass
